import {
  CustomDataSource,
  Cartographic,
  Ellipsoid,
  Color,
  Cartesian3,
  Math as CesiumMath,
  ArcType,
  ShadowMode,
  ClassificationType,
  HorizontalOrigin,
  VerticalOrigin,
  ColorMaterialProperty,
  ScreenSpaceEventHandler,
  Cartesian2,
  defined,
  SceneMode,
  ScreenSpaceEventType,
  ImageMaterialProperty
} from 'cesium';
import circlePic from '@/assets/largescreen/yuan-jiazai.png';
import { useCesiumPoints, popup } from '@/hooks/useCesiumPoints';

/**
 * Cesium 实体管理 Hook
 */
export function useCesiumEntity() {
  // 使用普通对象而非响应式，避免 Vue 响应式系统对 Cesium 对象的干扰
  let lineDataSource = {};
  let evacuationRoute = {};

  /**
   * 初始化变量，清空所有数据源
   */
  const initVariable = () => {
    // 重置数据源
    lineDataSource = {};
    evacuationRoute = {};
  };

  /**
   * 添加撤离路线
   * @param pip 路线坐标点数组
   * @param name 路线名称
   */
  const addGeo = (pip: number[][], name: string) => {
    if (Object.keys(evacuationRoute).length > 0) {
      if (Object.keys(evacuationRoute[name]).length > 0) {
        evacuationRoute[name].entities.removeAll();
        evacuationRoute[name] = {};
        return;
      }
    }

    evacuationRoute[name] = new CustomDataSource();
    window.viewer.dataSources.add(evacuationRoute[name]);

    const cartesianCoordinates = pip.map(function (coord) {
      const cartographic = Cartographic.fromDegrees(coord[0], coord[1]);
      return Ellipsoid.WGS84.cartographicToCartesian(cartographic);
    });

    evacuationRoute[name].entities.add({
      polyline: {
        positions: cartesianCoordinates,
        width: 5, // 管线宽度
        material: Color.GREEN.withAlpha(0.8) // 管线颜色和透明度
      }
    });
  };

  /**
   * 根据风险值获取颜色
   * @param value 风险值
   * @returns Color
   */
  const getColorByRisk = (value: number): Color => {
    if (value > 80 && value <= 100) {
      return Color.fromCssColorString('#FF0000');
    } else if (value > 60 && value <= 80) {
      return Color.fromCssColorString('#FFA500');
    } else if (value > 40 && value <= 60) {
      return Color.fromCssColorString('#FFFF00');
    } else if (value <= 40) {
      return Color.fromCssColorString('#00ffff');
    }
    return Color.WHITE;
  };

  /**
   * 添加管线
   * @param line 管线数据（JSON字符串）
   * @param lineData 管线风险数据（JSON字符串）
   */
  const addLine = (line: string, lineData: string) => {
    const data = JSON.parse(lineData);
    const pip = JSON.parse(line);

    if (!data) return;

    if (Object.keys(lineDataSource).length > 0) {
      pip.forEach((item: any, index: number) => {
        lineDataSource[index].entities.removeAll();
      });
      lineDataSource = {};
      return;
    }

    pip.forEach((item: number[], index: number) => {
      lineDataSource[index] = new CustomDataSource();
      window.viewer.dataSources.add(lineDataSource[index]);

      lineDataSource[index].entities.add({
        id: 'SurroundingPipe' + index,
        name:
          '管线ID:' +
          data[index].pipe_id +
          '\n' +
          '管线类型:' +
          data[index].pipe_type +
          '\n' +
          '关联风险值:' +
          Number(data[index].blast_risk).toFixed(2) +
          '\n' +
          '影响概率:' +
          (Number(data[index].blast_probability) * 100).toFixed(2) +
          '%',
        polyline: {
          show: true,
          positions: Cartesian3.fromDegreesArray(item),
          width: 3,
          granularity: CesiumMath.RADIANS_PER_DEGREE,
          material: getColorByRisk(50), // 写死只展示黄颜色的管线
          arcType: ArcType.NONE,
          clampToGround: false,
          shadows: ShadowMode.DISABLED,
          classificationType: ClassificationType.BOTH,
          zIndex: -10 // 设置为负值，确保在底层
        },
        description: data[index]
      });
    });
  };

  /**
   * 飞行到指定位置
   * @param data 包含经纬度的数据对象
   * @param height 飞行高度，默认1000
   */
  const flyTo = (data: { longitude: string | number; latitude: string | number }, height: number = 1000) => {
    window.viewer.camera.flyTo({
      destination: Cartesian3.fromDegrees(Number(data.longitude), Number(data.latitude), height),
      orientation: {
        heading: CesiumMath.toRadians(0),
        pitch: CesiumMath.toRadians(-90),
        roll: 0.0
      }
    });
  };

  /**
   * 创建标签
   * @param name 标签名称
   * @param radius 半径
   * @returns 标签配置对象
   */
  const createLabel = (name: string, radius: number) => {
    return {
      text: name + ':' + radius + '米',
      font: '14px monospace',
      background: Color.fromCssColorString('#DCDCDC'),
      showBackground: true,
      horizontalOrigin: HorizontalOrigin.CENTER,
      verticalOrigin: VerticalOrigin.CENTER,
      eyeOffset: new Cartesian3(0.0, radius, 100)
    };
  };

  /**
   * 绘制轻伤范围圆形
   * @param data 中心点数据
   * @param radius 半径
   */
  const drawPolygon = (data: { longitude: string | number; latitude: string | number }, radius: number) => {
    if (radius == 0) return;

    const viewer = window.viewer;
    const circle = {
      id: 'circle',
      name: '轻伤范围',
      position: Cartesian3.fromDegrees(Number(data.longitude), Number(data.latitude)),
      label: createLabel('轻伤范围', Number(Number(radius).toFixed(2))),
      ellipse: {
        semiMinorAxis: radius,
        semiMajorAxis: radius,
        material: new ColorMaterialProperty(Color.RED.withAlpha(0.3))
      }
    };
    viewer.entities.add(circle);
  };

  /**
   * 绘制周边资源范围圆形
   * @param data 中心点数据
   * @param radius 半径
   */
  const drawPolygon1 = (data: { longitude: string | number; latitude: string | number }, radius: number) => {
    const viewer = window.viewer;
    const circle = {
      id: 'circle1',
      name: '周边资源',
      position: Cartesian3.fromDegrees(Number(data.longitude), Number(data.latitude)),
      label: createLabel('周边资源', Number(Number(radius).toFixed(2))),
      ellipse: {
        semiMinorAxis: radius,
        semiMajorAxis: radius,
        material: new ImageMaterialProperty({
          image: circlePic
        })
      }
    };
    viewer.entities.add(circle);

    // 回归原版简单的鼠标事件处理
    const handler = new ScreenSpaceEventHandler(viewer.scene.canvas);
    const labelEntity = viewer.entities.add({
      label: {
        show: false,
        showBackground: true,
        font: '14px monospace',
        horizontalOrigin: HorizontalOrigin.LEFT,
        verticalOrigin: VerticalOrigin.TOP,
        pixelOffset: new Cartesian2(15, 0)
      }
    });

    // 简单直接的鼠标移入处理
    handler.setInputAction((e: any) => {
      let foundPosition = false;
      const pickedObject = viewer.scene.pick(e.endPosition);

      if (viewer.scene.pickPositionSupported && defined(pickedObject) && pickedObject.id !== '') {
        const cartesian = viewer.scene.pickPosition(e.endPosition);
        if (defined(cartesian)) {
          const cartographic = Cartographic.fromCartesian(cartesian);
          labelEntity.position = cartesian;
          labelEntity.label.show = true;
          labelEntity.label.text = pickedObject.id._name;
          labelEntity.label.eyeOffset = new Cartesian3(0.0, 0.0, -cartographic.height * (viewer.scene.mode === SceneMode.SCENE2D ? 1.5 : 1.0));
          foundPosition = true;
        }
      }

      if (!foundPosition) {
        labelEntity.label.show = false;
      }
    }, ScreenSpaceEventType.MOUSE_MOVE);
  };

  /**
   * 绘制扩散范围圆形
   * @param data 中心点数据
   * @param radius 半径
   */
  const drawPolygon2 = (data: { longitude: string | number; latitude: string | number }, radius: number) => {
    if (radius == 0) return;

    const viewer = window.viewer;
    const circle = {
      id: 'circle2',
      name: '扩散范围',
      position: Cartesian3.fromDegrees(Number(data.longitude), Number(data.latitude)),
      label: createLabel('扩散范围', Number(Number(radius).toFixed(2))),
      ellipse: {
        zIndex: 100,
        semiMinorAxis: radius,
        semiMajorAxis: radius,
        material: new ColorMaterialProperty(Color.BLUE.withAlpha(0.3))
      }
    };
    viewer.entities.add(circle);
  };

  /**
   * 绘制重伤范围圆形
   * @param data 中心点数据
   * @param radius 半径
   */
  const drawPolygon3 = (data: { longitude: string | number; latitude: string | number }, radius: number) => {
    if (radius == 0) return;

    const viewer = window.viewer;
    const circle = {
      id: 'circle3',
      name: '重伤范围',
      position: Cartesian3.fromDegrees(Number(data.longitude), Number(data.latitude)),
      label: createLabel('重伤范围', Number(Number(radius).toFixed(2))),
      ellipse: {
        semiMinorAxis: radius,
        semiMajorAxis: radius,
        material: new ColorMaterialProperty(Color.RED.withAlpha(0.8))
      }
    };
    viewer.entities.add(circle);
  };

  /**
   * 清除指定圆形
   * @param circleId 圆形ID
   */
  const clearPolygon = (circleId: string) => {
    const viewer = window.viewer;
    viewer.entities.removeById(circleId);
  };

  /**
   * 通过ID获取实体并创建弹窗
   * @param data 资源数据
   * @param dataSource 数据源数组
   * @param isIndividuallyOpen 是否单独打开
   */
  const getEntityById = (data: any, dataSource: any[], isIndividuallyOpen: boolean) => {
    if (data.level_two == '救援队伍') {
      data.level_two = '救援队';
    }

    if (isIndividuallyOpen) {
      for (const popupKey in popup) {
        popup[popupKey].remove();
      }
    }

    const entity = dataSource.find((item) => {
      const description = JSON.parse(item.description.getValue());
      return description.resource_id === data.resource_id;
    });

    if (entity) {
      useCesiumPoints().createPopUp(entity);
      flyTo(data);
    }
  };

  /**
   * 放大地图
   */
  const zoomIn = () => {
    const height = Cartographic.fromCartesian(window.viewer.camera.position).height;
    if (height < 1100) return;
    window.viewer.camera.zoomIn();
  };

  /**
   * 缩小地图
   */
  const zoomOut = () => {
    const height = Cartographic.fromCartesian(window.viewer.camera.position).height;
    if (height > 400000) return;
    window.viewer.camera.zoomOut();
  };

  /**
   * 解析LINESTRING格式的坐标字符串
   * @param lineString LINESTRING格式的字符串，如 "LINESTRING (117.8229010014802 36.07352669909801, 117.82291006394848 36.07353345930187)"
   * @returns 坐标数组 [[longitude, latitude], ...]
   */
  const parseLineString = (lineString: string): number[][] => {
    try {
      // 移除"LINESTRING ("和结尾的")"
      const coordsString = lineString.replace(/LINESTRING\s*\(\s*/, '').replace(/\s*\)$/, '');

      // 分割坐标对并解析
      const coordPairs = coordsString.split(',');
      const coordinates: number[][] = [];

      coordPairs.forEach((pair) => {
        const coords = pair.trim().split(/\s+/);
        if (coords.length >= 2) {
          const longitude = parseFloat(coords[0]);
          const latitude = parseFloat(coords[1]);
          if (!isNaN(longitude) && !isNaN(latitude)) {
            coordinates.push([longitude, latitude]);
          }
        }
      });

      return coordinates;
    } catch (error) {
      console.error('解析LINESTRING失败:', error);
      return [];
    }
  };

  /**
   * 通用管线绘制函数
   * @param lineString LINESTRING格式的坐标数据
   * @param color 管线颜色
   * @param id 实体ID
   * @param name 管线名称
   * @param width 管线宽度，默认5
   * @param zIndex 层级索引，数值越大越在上层，默认0
   */
  const drawPipeline = (lineString: string, color: Color, id: string, name: string, width: number = 5, zIndex: number = 0) => {
    const viewer = window.viewer;
    if (!viewer) return;

    // 清除已存在的同ID实体
    const existingEntity = viewer.entities.getById(id);
    if (existingEntity) {
      viewer.entities.remove(existingEntity);
    }

    const coordinates = parseLineString(lineString);
    if (coordinates.length < 2) {
      console.warn(`${name}坐标数据不足`);
      return;
    }

    const cartesianCoordinates = coordinates.map((coord) => {
      const longitude = typeof coord[0] === 'string' ? parseFloat(coord[0]) : coord[0];
      const latitude = typeof coord[1] === 'string' ? parseFloat(coord[1]) : coord[1];
      // 根据zIndex调整高度，让层级高的管线稍微高一点
      const height = zIndex * 0.1;
      return Cartesian3.fromDegrees(longitude, latitude, height);
    });

    viewer.entities.add({
      id: id,
      name: name,
      polyline: {
        positions: cartesianCoordinates,
        width: width,
        material: color,
        clampToGround: false, // 改为false以支持高度差异
        zIndex: zIndex // 设置层级
      }
    });
  };

  /**
   * 绘制热力管线（绿色）
   * @param lineString LINESTRING格式的坐标数据
   * @param id 实体ID
   * @param name 管线名称
   */
  const drawHeatPipeline = (lineString: string, id: string = 'heat_pipeline', name: string = '热力管线') => {
    drawPipeline(lineString, Color.GREEN, id, name, 5, 10); // 层级10
  };

  /**
   * 绘制轨交管线（蓝色）
   * @param lineString LINESTRING格式的坐标数据
   * @param id 实体ID
   * @param name 管线名称
   */
  const drawRailPipeline = (lineString: string, id: string = 'rail_pipeline', name: string = '轨道交通') => {
    drawPipeline(lineString, Color.BLUE, id, name, 5, 20); // 层级20
  };

  /**
   * 绘制溯源管线（红色）
   * @param lineString LINESTRING格式的坐标数据
   * @param id 实体ID
   * @param name 管线名称
   */
  const drawIntersectionPipeline = (lineString: string, id: string = 'intersection_pipeline', name: string = '溯源管线') => {
    drawPipeline(lineString, Color.RED, id, name, 6, 10); // 设置最高层级100
  };

  /**
   * 绘制距离连接线（紫色）
   * @param startPoint 起始点坐标 {longitude, latitude}
   * @param endPoint 结束点坐标 {longitude, latitude}
   * @param distance 距离值（米）
   * @param id 实体ID
   */
  const drawDistanceConnectionLine = (
    startPoint: { longitude: number; latitude: number },
    endPoint: { longitude: number; latitude: number },
    distance: number,
    id: string = 'distance_connection'
  ) => {
    const viewer = window.viewer;
    if (!viewer) return;

    // 当距离为0时不绘制连接线
    if (distance === 0) {
      console.log('距离为0，不绘制连接线');
      return;
    }

    // 清除已存在的同ID实体
    const existingLineEntity = viewer.entities.getById(id);
    if (existingLineEntity) {
      viewer.entities.remove(existingLineEntity);
    }
    const existingLabelEntity = viewer.entities.getById(id + '_label');
    if (existingLabelEntity) {
      viewer.entities.remove(existingLabelEntity);
    }

    const startLng = typeof startPoint.longitude === 'string' ? parseFloat(startPoint.longitude) : startPoint.longitude;
    const startLat = typeof startPoint.latitude === 'string' ? parseFloat(startPoint.latitude) : startPoint.latitude;
    const endLng = typeof endPoint.longitude === 'string' ? parseFloat(endPoint.longitude) : endPoint.longitude;
    const endLat = typeof endPoint.latitude === 'string' ? parseFloat(endPoint.latitude) : endPoint.latitude;

    const startPos = Cartesian3.fromDegrees(startLng, startLat);
    const endPos = Cartesian3.fromDegrees(endLng, endLat);

    // 绘制紫色连接线
    viewer.entities.add({
      id: id,
      name: '距离连接线',
      polyline: {
        positions: [startPos, endPos],
        width: 4,
        material: Color.PURPLE,
        clampToGround: true
      }
    });

    // 添加距离标签
    const midPoint = Cartesian3.lerp(startPos, endPos, 0.5, new Cartesian3());
    viewer.entities.add({
      id: id + '_label',
      position: midPoint,
      label: {
        text: `${distance.toFixed(2)}m`,
        font: '16px Arial',
        style: 2,
        outlineWidth: 2,
        verticalOrigin: 0,
        fillColor: Color.WHITE,
        outlineColor: Color.BLACK,
        showBackground: true,
        backgroundColor: Color.PURPLE.withAlpha(0.8),
        backgroundPadding: new Cartesian3(8, 4)
      }
    });
  };

  return {
    // 方法
    initVariable,
    addGeo,
    addLine,
    flyTo,
    drawPolygon,
    drawPolygon1,
    drawPolygon2,
    drawPolygon3,
    clearPolygon,
    getEntityById,
    zoomIn,
    zoomOut,
    parseLineString,
    drawPipeline,
    drawHeatPipeline,
    drawRailPipeline,
    drawIntersectionPipeline,
    drawDistanceConnectionLine
  };
}
